package com.chen.shopping_seckill_customer_api.controller;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.shopping_common.pojo.Orders;
import com.chen.shopping_common.pojo.SeckillGoods;
import com.chen.shopping_common.result.BaseResult;
import com.chen.shopping_common.service.OrderService;
import com.chen.shopping_common.service.SeckillService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user/seckillGoods")
public class SeckillGoodsController {

    @DubboReference
    private SeckillService service;
    @DubboReference
    private OrderService orderService;

    @GetMapping("/findPage")
    public BaseResult<Page<SeckillGoods>> findByRedis(int page,int size) throws InterruptedException {
        Page<SeckillGoods> pageByRedis = service.findPageByRedis(page, size);
        return BaseResult.ok(pageByRedis);
    }

    @GetMapping("/findById")
    public BaseResult<SeckillGoods> findById(Long id){
        //从Redis中查询
        SeckillGoods seckillGoodsByRedis = service.findSeckillGoodsByRedis(id);
        //Redis中没有，从数据库中查询
        if (seckillGoodsByRedis != null){
            return BaseResult.ok(seckillGoodsByRedis);
        }else {
            SeckillGoods seckillGoodsByMysql = service.findSeckillGoodsByMysql(id);
            return BaseResult.ok(seckillGoodsByMysql);
        }

    }

    @PostMapping("/add")
    public BaseResult<Orders> add(@RequestBody Orders orders , @RequestHeader Long userId){
        orders.setUserId(userId);
        Orders orders1 = service.addSeckillGoodsOrder(orders);
        return BaseResult.ok(orders1);
    }

    //在redis中查询秒杀订单
    @GetMapping("/findOrder")
    public BaseResult<Orders> findOrder(String id){
        Orders orders = service.findByOrderId(id);
        return BaseResult.ok(orders);
    }

    /**
     * 支付秒杀订单
     */
    @GetMapping("/pay")
    public BaseResult pay(String id){
        Orders orders = service.pay(id);
        //将订单保存到数据库中
        orderService.add(orders);
        return BaseResult.ok();
    }
}
